/*
 * connection.hpp
 *
 *  Created on: Dec 5, 2010
 *      Author: daniel
 */

#ifndef H_CONNECTION_HPP_
#define H_CONNECTION_HPP_

#include <boost/utility.hpp>
#include <boost/asio.hpp>
//#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
//#include <boost/weak_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <map>
#include <string>
//#include <doeplus/webapp/protocol/iconnection.hpp>
#include <doeplus/webapp/defines.hpp>

namespace doeplus{ namespace webapp{

class server;

class connection : public boost::enable_shared_from_this<connection> {

public:
//	typedef std::map<std::string,std::string> stringmap;
	typedef boost::shared_ptr<connection> ptr;

	ptr get_ptr(){
		return this->shared_from_this();
	}
public:
	std::string request_method;
	std::string request_uri;
	std::string request_path;

	bool response_complete;
	bool response_headers_send;
	int response_code;

	/*
	 * _variables contains all parameters send by the webserver.
	 */
	string_map _variables;
	string_map _response_headers;

protected:
	void parse_request_uri(){
		std::size_t path_split(this->request_uri.find("?"));
		if(path_split==std::string::npos){
			this->request_path	= this->request_uri;
		}else{
			this->request_path.assign(this->request_uri.c_str(),path_split);
		}
	}

public:
	const char* request_header(char *key){
		string_map::iterator it(this->_variables.find(key));
		if(it!=this->_variables.end()){
			return it->second.c_str();
		}
		return NULL;
	}
	/**
	 * Set headers to send. Will return false if headers has already been send
	 */
	bool response_header(std::string header,std::string content,bool replace=true){
		return true;
	}

public:
	virtual void handle_write(const boost::system::error_code& error) = 0;
	virtual void handle_read(const boost::system::error_code& error,std::size_t bytes_transferred) = 0;

public:

	connection(string_map &default_headers) :
		response_complete(false),
		response_headers_send(false),
		response_code(200),
		_response_headers(default_headers)
	{

	}

	virtual ~connection(){}

	virtual void start(doeplus::webapp::server* _server){}

	virtual void send_response(const std::string& response,bool last_response=false){}

public:

};

} } // doeplus::webapp

#endif
